#!/bin/bash

# Git项目更新飞书推送脚本
# 支持从环境变量获取Git平台数据并推送到飞书

# 飞书Webhook URL
FEISHU_WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/ae170f41-0f1b-4643-bc4a-0919dc900f7e"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'

# 格式化变更文件列表
format_changed_files() {
    local files="$1"
    if [ -n "$files" ]; then
        # 将文件列表格式化为每行一个文件，并添加缩进
        echo "$files" | sed 's/^/         /' | sed ':a;N;$!ba;s/\n/\\n/g'
    else
        echo "   无文件变更"
    fi
}

# 获取提交ID的短版本（前8位）
get_short_commit_id() {
    local commit_id="$1"
    if [ -n "$commit_id" ]; then
        echo "${commit_id:0:8}"
    else
        echo "未知"
    fi
}

# 格式化提交信息（限制长度）
format_commit_message() {
    local message="$1"
    if [ -n "$message" ]; then
        # 限制提交信息长度为50个字符
        if [ ${#message} -gt 50 ]; then
            echo "${message:0:47}..."
        else
            echo "$message"
        fi
    else
        echo "无提交信息"
    fi
}

# 构建飞书消息内容
build_feishu_message() {
    local platform="${GIT_PLATFORM:-未知平台}"
    local repo_name="${GIT_REPO_NAME:-未知仓库}"
    local repo_url="${GIT_REPO_URL:-#}"
    local branch="${GIT_BRANCH:-未知分支}"
    local commit_id="${GIT_COMMIT_ID:-}"
    local commit_message="${GIT_COMMIT_MESSAGE:-}"
    local author="${GIT_AUTHOR:-未知作者}"
    local committer="${GIT_COMMITTER:-未知提交者}"
    local files_changed="${GIT_FILES_CHANGED:-}"
    
    local short_commit_id=$(get_short_commit_id "$commit_id")
    local formatted_message=$(format_commit_message "$commit_message")
    local formatted_files=$(format_changed_files "$files_changed")
    
    cat << EOF
{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "🚀 Git项目更新通知",
                "content": [
                    [{
                        "tag": "text",
                        "text": "📦 仓库信息"
                    }],
                    [{
                        "tag": "text",
                        "text": "   平台类型: "
                    }, {
                        "tag": "text",
                        "text": "$platform",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   仓库名称: "
                    }, {
                        "tag": "text",
                        "text": "$repo_name",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   分支名称: "
                    }, {
                        "tag": "text",
                        "text": "$branch",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   仓库地址: "
                    }, {
                        "tag": "a",
                        "text": "点击查看",
                        "href": "$repo_url"
                    }],
                    [{
                        "tag": "text",
                        "text": ""
                    }],
                    [{
                        "tag": "text",
                        "text": "📝 提交信息"
                    }],
                    [{
                        "tag": "text",
                        "text": "   提交ID: "
                    }, {
                        "tag": "text",
                        "text": "$short_commit_id",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   提交信息: "
                    }, {
                        "tag": "text",
                        "text": "$formatted_message",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   作者: "
                    }, {
                        "tag": "text",
                        "text": "$author",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": "   提交者: "
                    }, {
                        "tag": "text",
                        "text": "$committer",
                        "style": "bold"
                    }],
                    [{
                        "tag": "text",
                        "text": ""
                    }],
                    [{
                        "tag": "text",
                        "text": "📁 变更文件"
                    }],
                    [{
                        "tag": "text",
                        "text": "$formatted_files",
                        "style": "italic"
                    }],
                    [{
                        "tag": "text",
                        "text": ""
                    }],
                    [{
                        "tag": "text",
                        "text": "⏰ 推送时间: "
                    }, {
                        "tag": "text",
                        "text": "$(date '+%Y-%m-%d %H:%M:%S')",
                        "style": "bold"
                    }]
                ]
            }
        }
    }
}
EOF
}

# 发送飞书消息
send_feishu_message() {
    local message="$1"
    
    echo -e "${CYAN}正在发送飞书消息...${NC}"
    
    # 发送HTTP请求
    local response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "$message" \
        "$FEISHU_WEBHOOK_URL")
    
    # 检查响应
    if echo "$response" | grep -q '"code":0'; then
        echo -e "${GREEN}✅ 飞书消息发送成功！${NC}"
        return 0
    else
        echo -e "${RED}❌ 飞书消息发送失败${NC}"
        echo -e "${YELLOW}响应内容: $response${NC}"
        return 1
    fi
}

# 显示Git信息
show_git_info() {
    echo -e "${CYAN}=== Git项目信息 ===${NC}"
    echo -e "${WHITE}平台类型:${NC} ${GIT_PLATFORM:-未设置}"
    echo -e "${WHITE}仓库名称:${NC} ${GIT_REPO_NAME:-未设置}"
    echo -e "${WHITE}仓库地址:${NC} ${GIT_REPO_URL:-未设置}"
    echo -e "${WHITE}分支名称:${NC} ${GIT_BRANCH:-未设置}"
    echo -e "${WHITE}提交ID:${NC} ${GIT_COMMIT_ID:-未设置}"
    echo -e "${WHITE}提交信息:${NC} ${GIT_COMMIT_MESSAGE:-未设置}"
    echo -e "${WHITE}作者:${NC} ${GIT_AUTHOR:-未设置}"
    echo -e "${WHITE}提交者:${NC} ${GIT_COMMITTER:-未设置}"
    if [ -n "$GIT_FILES_CHANGED" ]; then
        echo -e "${WHITE}变更文件:${NC}"
        echo -e "$GIT_FILES_CHANGED" | sed 's/^/  /'
    else
        echo -e "${WHITE}变更文件:${NC} 未设置"
    fi
    echo
}

# 主函数
main() {
    echo -e "${GREEN}🚀 Git项目更新飞书推送脚本${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 显示Git信息
    show_git_info
    
    # 检查必要的环境变量
    if [ -z "$GIT_REPO_NAME" ] && [ -z "$GIT_COMMIT_ID" ]; then
        echo -e "${YELLOW}⚠️  警告: 未检测到Git环境变量${NC}"
        echo -e "${CYAN}请确保在Git环境中运行此脚本，或手动设置以下环境变量:${NC}"
        echo -e "${WHITE}  GIT_PLATFORM, GIT_REPO_NAME, GIT_REPO_URL, GIT_BRANCH${NC}"
        echo -e "${WHITE}  GIT_COMMIT_ID, GIT_COMMIT_MESSAGE, GIT_AUTHOR, GIT_COMMITTER${NC}"
        echo -e "${WHITE}  GIT_FILES_CHANGED${NC}"
        echo
    fi
    
    # 构建消息
    echo -e "${CYAN}构建飞书消息...${NC}"
    local message=$(build_feishu_message)
    
    # 发送消息
    send_feishu_message "$message"
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}脚本执行完成${NC}"
    echo
}

# 如果直接运行此脚本，执行主函数
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
